package com.rtsapp.server.benchmark.script;

import com.rtsapp.server.common.ByteBuffer;
import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;
import com.rtsapp.server.network.protocol.command.ICommand;
/**
 *  一个日志最小长度为 28 个长度
 */
public class ScriptCommand {

    private static final Logger LOGGER = LoggerFactory.getLogger( ScriptCommand.class );

    /**
     * 命令类型
     */
    public enum CommandType{
        /**
         * 请求
         */
        Req( 0 ),
        /**
         * 响应
         */
        Resp( 1 )
        ;

        int value;
        CommandType( int type ){
            this.value = type;
        }

        public int getValue( ){
            return value;
        }

    }

    /**
     * 命令日志格式: size, userid, command_type, msec, commandid,  commandbuffer(里面还有一个commandid)
     */
    public static void writeCommand(ScriptCommand.CommandType type, int userId, ICommand command, ByteBuffer buffer) {

        // 长度占位处先写入0, 记录原有长度
        int oldSize = buffer.readableBytes();
        int writeIndex = buffer.writeIndex();


        buffer.writeInt( 0 );

        buffer.writeInt(userId);
        buffer.writeInt(type.getValue());
        buffer.writeLong(System.currentTimeMillis());
        buffer.writeInt(command.getCommandId());

        command.writeToBuffer(buffer);

        // 占位符处换上真实的长度
        buffer.setInt( writeIndex,  buffer.readableBytes() - oldSize );
    }


    /**
     * 每一个命令日志的消息至少为28字节
     */
    public static final int HEAD_LENGTH = 28;

    private int userId;
    private CommandType type;
    private long timestamp;
    private int commandId;
    private ICommand command;

    public void readFromBuffer( ByteBuffer buffer, IScriptCommandFactory factory ){
        userId = buffer.readInt();

        int t = buffer.readInt();
        this.type = (  t == CommandType.Req.getValue() ) ? CommandType.Req : CommandType.Resp;

        timestamp = buffer.readLong();
        commandId = buffer.readInt();

        if( this.type == CommandType.Req ){
            command = factory.createRequest( commandId );
        }else{
            command = factory.createResponse( commandId );
        }

        if( command != null ){
            try {
                command.readFromBuffer(buffer);
            }catch( Throwable ex ){
                LOGGER.error( "ScriptCommand readFromBuffer error", ex );
            }
        }
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public int getUserId() {
        return userId;
    }

    public CommandType getType() {
        return type;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public int getCommandId() {
        return commandId;
    }

    public ICommand getCommand() {
        return command;
    }
}
